{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 卷积神经网络"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Extracting MNIST_data\\train-images-idx3-ubyte.gz\n",
      "Extracting MNIST_data\\train-labels-idx1-ubyte.gz\n",
      "Extracting MNIST_data\\t10k-images-idx3-ubyte.gz\n",
      "Extracting MNIST_data\\t10k-labels-idx1-ubyte.gz\n",
      "h_conv1.shape:  [None, 28, 28, 32]\n",
      "h_pool1.shape:  [None, 14, 14, 32]\n",
      "h_conv2.shape:  [None, 14, 14, 64]\n",
      "h_pool2.shape:  [None, 7, 7, 64]\n",
      "Start optimizing\n",
      "Iter: 0, Testing Accuracy: 0.8526\n",
      "Iter: 10, Testing Accuracy: 0.9864\n",
      "Iter: 20, Testing Accuracy: 0.9875\n",
      "Iter: 30, Testing Accuracy: 0.9905\n",
      "Iter: 40, Testing Accuracy: 0.9908\n",
      "Iter: 50, Testing Accuracy: 0.9918\n",
      "completed\n"
     ]
    }
   ],
   "source": [
    "import tensorflow as tf\n",
    "from tensorflow.examples.tutorials.mnist import input_data\n",
    "\n",
    "# 命名空间清空\n",
    "tf.reset_default_graph()\n",
    "\n",
    "# 载入数据集\n",
    "mnist=input_data.read_data_sets(\"MNIST_data\",one_hot=True)\n",
    "\n",
    "#每个批次的大小\n",
    "batch_size = 100\n",
    "#计算一共有多少个批次\n",
    "n_batch = mnist.train.num_examples // batch_size\n",
    "\n",
    "# 初始化权值\n",
    "def weight_varible(shape):\n",
    "    initial=tf.truncated_normal(shape,stddev=0.1)\n",
    "    return tf.Variable(initial)\n",
    "\n",
    "def bias_varible(shape):\n",
    "    initial=tf.constant(0.1,shape=shape)\n",
    "    return tf.Variable(initial)\n",
    "\n",
    "# 卷积层(具体函数的定义需要进一步看文档)\n",
    "def conv2d(x,W):\n",
    "    return tf.nn.conv2d(x,W,strides=[1,1,1,1],padding='SAME')\n",
    "\n",
    "# 池化层(具体函数的定义需要进一步看文档)\n",
    "def max_pool_2x2(x):\n",
    "    return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')\n",
    "\n",
    "# 定义两个placeholder\n",
    "x=tf.placeholder(tf.float32,[None,784])\n",
    "y=tf.placeholder(tf.float32,[None,10])\n",
    "\n",
    "# 改变x的格式转为4D向量[batch,in_height,in_width,in_channels]\n",
    "x_image=tf.reshape(x,[-1,28,28,1])\n",
    "\n",
    "# 初始化第一个卷积层的权值和偏置\n",
    "W_convl=weight_varible([5,5,1,32])#5x5的采样窗口，32个卷积核，从1个平面抽取特征\n",
    "b_conv1=bias_varible([32])# 每一个卷积核一个偏置值\n",
    "\n",
    "# 把x_image和权值进项向量卷积，加上偏置值，然后用relu激活\n",
    "h_conv1=tf.nn.relu(conv2d(x_image,W_convl)+b_conv1)\n",
    "print ('h_conv1.shape: ', h_conv1.get_shape().as_list())\n",
    "h_pool1=max_pool_2x2(h_conv1)\n",
    "print ('h_pool1.shape: ', h_pool1.get_shape().as_list())\n",
    "\n",
    "# 初始化第二个卷积层的权值和偏置\n",
    "W_conv2=weight_varible([5,5,32,64])#5x5的采样窗口，64个卷积核，从32个平面抽取特征\n",
    "b_conv2=bias_varible([64])# 每一个卷积核一个偏置值\n",
    "\n",
    "# 把h_pool1和权值进项向量卷积，加上偏置值，然后用relu激活\n",
    "h_conv2=tf.nn.relu(conv2d(h_pool1,W_conv2)+b_conv2)\n",
    "print ('h_conv2.shape: ', h_conv2.get_shape().as_list())\n",
    "h_pool2=max_pool_2x2(h_conv2)\n",
    "print ('h_pool2.shape: ', h_pool2.get_shape().as_list())\n",
    "\n",
    "# 28x28的图片第一次卷积后还是28*28，第一次池化之后就是14x14\n",
    "# 第二次卷积后是14x14，池化后是7x7\n",
    "# 上面操作后得到64个7x7的平面\n",
    "\n",
    "# 初始化全连接层的权值\n",
    "W_fc1=weight_varible([7*7*64,1024]) # 上一层有7*7*64个神经元，全连接层1024个\n",
    "b_fc1=bias_varible([1024]) # 1024个节点\n",
    "\n",
    "# 把池化层2的输出扁平化为1维\n",
    "h_pool2_flat=tf.reshape(h_pool2,[-1,7*7*64])\n",
    "# 求第一个全连接层的输出\n",
    "h_fc1=tf.nn.relu(tf.matmul(h_pool2_flat,W_fc1)+b_fc1)\n",
    "\n",
    "# keep_prob用来表示神经元的输出概率\n",
    "keep_prob=tf.placeholder(tf.float32)\n",
    "h_fc1_drop=tf.nn.dropout(h_fc1,keep_prob)\n",
    "\n",
    "# 初始化第二个全连接层\n",
    "W_fc2=weight_varible([1024,10])\n",
    "b_fc2=bias_varible([10])\n",
    "\n",
    "# 计算输出\n",
    "prediction=tf.nn.softmax(tf.matmul(h_fc1_drop,W_fc2)+b_fc2)\n",
    "\n",
    "# 交叉熵代价函数\n",
    "loss=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=prediction))\n",
    "# Adamq求解最优值\n",
    "train_step=tf.train.AdamOptimizer(1e-4).minimize(loss)\n",
    "# 结果存放在一个布尔值表中\n",
    "correct_prediction=tf.equal(tf.argmax(prediction,1),tf.argmax(y,1))\n",
    "# 求准确率\n",
    "accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32))\n",
    "\n",
    "# 开始进行求解\n",
    "print('Start optimizing')\n",
    "with tf.Session() as sess:\n",
    "    sess.run(tf.global_variables_initializer())\n",
    "    for epoch in range(51):\n",
    "        for batch in range(n_batch):\n",
    "            batch_xs,batch_ys=mnist.train.next_batch(batch_size)\n",
    "            sess.run(train_step,feed_dict={x:batch_xs,y:batch_ys,keep_prob:0.7})\n",
    "        \n",
    "        if epoch%10==0:\n",
    "            acc=sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels,keep_prob:0.7})\n",
    "            print(\"Iter: \"+str(epoch)+\", Testing Accuracy: \"+str(acc))\n",
    "\n",
    "print('completed')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "collapsed": true,
    "scrolled": true
   },
   "source": [
    "这里其实踩坑了，主要原因是每层的输出必须和输入匹配，检测的方式就是用下面这个语句：\n",
    "```Python\n",
    "print ('h_conv2.shape: ', h_conv2.get_shape().as_list())\n",
    "```\n",
    "观测每一层的输入和输出"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 想试试GPU的速度\n",
    "后来发现速度快的不是一点点，一个小时的活，一下子就给干完了，社会社会，能用GPU还是gu乖乖地用GPU吧。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Extracting MNIST_data\\train-images-idx3-ubyte.gz\n",
      "Extracting MNIST_data\\train-labels-idx1-ubyte.gz\n",
      "Extracting MNIST_data\\t10k-images-idx3-ubyte.gz\n",
      "Extracting MNIST_data\\t10k-labels-idx1-ubyte.gz\n",
      "h_conv1.shape:  [None, 28, 28, 32]\n",
      "h_pool1.shape:  [None, 14, 14, 32]\n",
      "h_conv2.shape:  [None, 14, 14, 64]\n",
      "h_pool2.shape:  [None, 7, 7, 64]\n",
      "WARNING:tensorflow:From <ipython-input-1-873ff089c0e9>:85: softmax_cross_entropy_with_logits (from tensorflow.python.ops.nn_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "\n",
      "Future major versions of TensorFlow will allow gradients to flow\n",
      "into the labels input on backprop by default.\n",
      "\n",
      "See tf.nn.softmax_cross_entropy_with_logits_v2.\n",
      "\n",
      "Start optimizing\n",
      "Iter: 0, Testing Accuracy: 0.9399\n",
      "Iter: 10, Testing Accuracy: 0.9869\n",
      "Iter: 20, Testing Accuracy: 0.9895\n",
      "Iter: 30, Testing Accuracy: 0.9915\n",
      "Iter: 40, Testing Accuracy: 0.9914\n",
      "Iter: 50, Testing Accuracy: 0.9909\n",
      "completed\n"
     ]
    }
   ],
   "source": [
    "# 来试试GPU的速度咋样\n",
    "import tensorflow as tf\n",
    "from tensorflow.examples.tutorials.mnist import input_data\n",
    "\n",
    "# 命名空间清空\n",
    "tf.reset_default_graph()\n",
    "\n",
    "# 载入数据集\n",
    "mnist=input_data.read_data_sets(\"MNIST_data\",one_hot=True)\n",
    "\n",
    "#每个批次的大小\n",
    "batch_size = 100\n",
    "#计算一共有多少个批次\n",
    "n_batch = mnist.train.num_examples // batch_size\n",
    "\n",
    "# 初始化权值\n",
    "def weight_varible(shape):\n",
    "    initial=tf.truncated_normal(shape,stddev=0.1)\n",
    "    return tf.Variable(initial)\n",
    "\n",
    "def bias_varible(shape):\n",
    "    initial=tf.constant(0.1,shape=shape)\n",
    "    return tf.Variable(initial)\n",
    "\n",
    "# 卷积层(具体函数的定义需要进一步看文档)\n",
    "def conv2d(x,W):\n",
    "    return tf.nn.conv2d(x,W,strides=[1,1,1,1],padding='SAME')\n",
    "\n",
    "# 池化层(具体函数的定义需要进一步看文档)\n",
    "def max_pool_2x2(x):\n",
    "    return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')\n",
    "\n",
    "# 定义两个placeholder\n",
    "x=tf.placeholder(tf.float32,[None,784])\n",
    "y=tf.placeholder(tf.float32,[None,10])\n",
    "\n",
    "# 改变x的格式转为4D向量[batch,in_height,in_width,in_channels]\n",
    "x_image=tf.reshape(x,[-1,28,28,1])\n",
    "\n",
    "# 初始化第一个卷积层的权值和偏置\n",
    "W_convl=weight_varible([5,5,1,32])#5x5的采样窗口，32个卷积核，从1个平面抽取特征\n",
    "b_conv1=bias_varible([32])# 每一个卷积核一个偏置值\n",
    "\n",
    "# 把x_image和权值进项向量卷积，加上偏置值，然后用relu激活\n",
    "h_conv1=tf.nn.relu(conv2d(x_image,W_convl)+b_conv1)\n",
    "print ('h_conv1.shape: ', h_conv1.get_shape().as_list())\n",
    "h_pool1=max_pool_2x2(h_conv1)\n",
    "print ('h_pool1.shape: ', h_pool1.get_shape().as_list())\n",
    "\n",
    "# 初始化第二个卷积层的权值和偏置\n",
    "W_conv2=weight_varible([5,5,32,64])#5x5的采样窗口，64个卷积核，从32个平面抽取特征\n",
    "b_conv2=bias_varible([64])# 每一个卷积核一个偏置值\n",
    "\n",
    "# 把h_pool1和权值进项向量卷积，加上偏置值，然后用relu激活\n",
    "h_conv2=tf.nn.relu(conv2d(h_pool1,W_conv2)+b_conv2)\n",
    "print ('h_conv2.shape: ', h_conv2.get_shape().as_list())\n",
    "h_pool2=max_pool_2x2(h_conv2)\n",
    "print ('h_pool2.shape: ', h_pool2.get_shape().as_list())\n",
    "\n",
    "# 28x28的图片第一次卷积后还是28*28，第一次池化之后就是14x14\n",
    "# 第二次卷积后是14x14，池化后是7x7\n",
    "# 上面操作后得到64个7x7的平面\n",
    "\n",
    "# 初始化全连接层的权值\n",
    "W_fc1=weight_varible([7*7*64,1024]) # 上一层有7*7*64个神经元，全连接层1024个\n",
    "b_fc1=bias_varible([1024]) # 1024个节点\n",
    "\n",
    "# 把池化层2的输出扁平化为1维\n",
    "h_pool2_flat=tf.reshape(h_pool2,[-1,7*7*64])\n",
    "# 求第一个全连接层的输出\n",
    "h_fc1=tf.nn.relu(tf.matmul(h_pool2_flat,W_fc1)+b_fc1)\n",
    "\n",
    "# keep_prob用来表示神经元的输出概率\n",
    "keep_prob=tf.placeholder(tf.float32)\n",
    "h_fc1_drop=tf.nn.dropout(h_fc1,keep_prob)\n",
    "\n",
    "# 初始化第二个全连接层\n",
    "W_fc2=weight_varible([1024,10])\n",
    "b_fc2=bias_varible([10])\n",
    "\n",
    "# 计算输出\n",
    "prediction=tf.nn.softmax(tf.matmul(h_fc1_drop,W_fc2)+b_fc2)\n",
    "\n",
    "# 交叉熵代价函数\n",
    "loss=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=prediction))\n",
    "# Adamq求解最优值\n",
    "train_step=tf.train.AdamOptimizer(1e-4).minimize(loss)\n",
    "# 结果存放在一个布尔值表中\n",
    "correct_prediction=tf.equal(tf.argmax(prediction,1),tf.argmax(y,1))\n",
    "# 求准确率\n",
    "accuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32))\n",
    "\n",
    "# 开始进行求解\n",
    "print('Start optimizing')\n",
    "with tf.Session() as sess:\n",
    "    sess.run(tf.global_variables_initializer())\n",
    "    for epoch in range(51):\n",
    "        for batch in range(n_batch):\n",
    "            batch_xs,batch_ys=mnist.train.next_batch(batch_size)\n",
    "            sess.run(train_step,feed_dict={x:batch_xs,y:batch_ys,keep_prob:0.7})\n",
    "        \n",
    "        if epoch%10==0:\n",
    "            acc=sess.run(accuracy,feed_dict={x:mnist.test.images,y:mnist.test.labels,keep_prob:0.7})\n",
    "            print(\"Iter: \"+str(epoch)+\", Testing Accuracy: \"+str(acc))\n",
    "\n",
    "print('completed')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
